/*
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <devmon/driver_abi.h>
#include <dlfcn.h>
#include <gtest/gtest.h>
#include <test_utilities/test_base.h>

#include "../../../drivers/bus/i2c/i2c.h"
#include "../../../drivers/chip/smc/smc.h"
#include "../../../drivers/internal/hasdef.h"
#include "../../../drivers/chip/interface/i_chip.h"
#include "../../test_utils/root_object.h"

using namespace dev;
using namespace devmon;

namespace drivers {
namespace chip {
namespace smc_test {

class smc_test_service : public mc::engine::service {
public:
    smc_test_service(const std::string& name) : mc::engine::service(name) {
    }
};

class SmcAbiTest : public mc::test::TestWithEngine {
public:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        // 动态创建服务实例，避免全局静态初始化导致的析构顺序问题
        m_test_service = mc::make_shared<smc_test_service>("bmc.kepler.test_smc");
        m_test_service->init();
        m_test_service->start();

        // 创建根对象
        m_root_object = root_object::create_root_object(m_test_service.get());

        load_driver();
    }

    static void TearDownTestSuite() {
        m_test_service->stop();
        m_root_object.reset();

        // 清理设备容器，避免引用已关闭的动态库
        m_devices.clear();
        m_i2c_devices.clear();

        // 不手动dlclose，避免静态对象析构时访问已卸载的动态库导致SIGSEGV
        // 让系统在程序退出时自动卸载动态库
        m_test_service.reset();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
        // 底层驱动打桩会自动管理内存，无需手动清理
    }

    void TearDown() override {
        // 底层驱动打桩会自动管理内存，无需手动清理
    }

    static void load_driver() {
        // 加载SMC驱动
        m_driver_handle = dlopen("./opt/bmc/drivers/libSmc.so", RTLD_LAZY);
        if (m_driver_handle == nullptr) {
            MC_THROW(mc::system_exception, "Failed to load Smc driver: ${error}",
                     ("error", dlerror()));
        }
        register_device_driver_func func = reinterpret_cast<register_device_driver_func>(
            dlsym(m_driver_handle, "register_device_driver"));
        MC_ASSERT_THROW(func, mc::bad_function_call_exception,
                        "Failed to get register_device_driver function: ${error}",
                        ("error", dlerror()));

        device_driver_t* devices       = nullptr;
        uint8_t          devices_count = 0;
        status_t         ret           = func(&devices, &devices_count);
        MC_ASSERT_THROW(ret == STATUS_OK, mc::bad_function_call_exception,
                        "Failed to get device driver manager: ${error}", ("error", ret));

        m_devices.clear();
        m_devices.reserve(devices_count);
        for (uint8_t i = 0; i < devices_count; i++) {
            auto device_driver = std::make_shared<device_driver_t>(devices[i]);
            m_devices.emplace(device_driver->device_name, device_driver);
        }

        // 加载I2C驱动
        m_i2c_driver_handle = dlopen("./opt/bmc/drivers/libI2c.so", RTLD_LAZY);
        if (m_i2c_driver_handle == nullptr) {
            MC_THROW(mc::system_exception, "Failed to load I2c driver: ${error}",
                     ("error", dlerror()));
        }
        register_device_driver_func i2c_func = reinterpret_cast<register_device_driver_func>(
            dlsym(m_i2c_driver_handle, "register_device_driver"));
        MC_ASSERT_THROW(i2c_func, mc::bad_function_call_exception,
                        "Failed to get I2c register_device_driver function: ${error}",
                        ("error", dlerror()));

        device_driver_t* i2c_devices       = nullptr;
        uint8_t          i2c_devices_count = 0;
        status_t         i2c_ret           = i2c_func(&i2c_devices, &i2c_devices_count);
        MC_ASSERT_THROW(i2c_ret == STATUS_OK, mc::bad_function_call_exception,
                        "Failed to get I2c device driver manager: ${error}", ("error", i2c_ret));

        m_i2c_devices.clear();
        m_i2c_devices.reserve(i2c_devices_count);
        for (uint8_t i = 0; i < i2c_devices_count; i++) {
            auto device_driver = std::make_shared<device_driver_t>(i2c_devices[i]);
            m_i2c_devices.emplace(device_driver->device_name, device_driver);
        }
    }

    std::shared_ptr<device_driver> create_bus_driver(const std::string& driver_name) {
        auto it = m_i2c_devices.find(driver_name);
        if (it == m_i2c_devices.end()) {
            MC_THROW(mc::invalid_op_exception, "I2c driver not found: ${name}", ("name", driver_name));
        }
        return it->second;
    }

    mc::dict create_test_connector(uint8_t system_id = 1, uint8_t position = 1, uint8_t slot = 1) {
        return {{"SystemId", system_id}, {"Position", position}, {"Slot", slot}};
    }

    mc::dict create_bus_csr_object(uint8_t bus_id, uint32_t bus_speed, uint8_t bus_mode,
                                   uint8_t bus_slave_addr, bool bus_use_smbus) {
        return {{"BusId", bus_id},
                {"BusSpeed", bus_speed},
                {"BusMode", bus_mode},
                {"BusSlaveAddr", bus_slave_addr},
                {"BusUseSmbus", bus_use_smbus}};
    }

    mc::mutable_dict create_smc_csr_object(uint32_t address, uint8_t offset_width, uint8_t address_width,
        uint32_t write_timeout, uint32_t read_timeout,
        uint8_t rw_block_size, uint8_t write_interval,
        uint8_t read_interval, uint8_t write_retry, uint8_t read_retry) {
        return {{"Address", address},
                {"OffsetWidth", offset_width},
                {"AddrWidth", address_width},
                {"WriteTmout", write_timeout},
                {"ReadTmout", read_timeout},
                {"RwBlockSize", rw_block_size},
                {"WriteInterval", write_interval},
                {"ReadInterval", read_interval},
                {"WriteRetryTimes", write_retry},
                {"ReadRetryTimes", read_retry},
                {"object_name", "test_i2c"}};
    }

protected:
    static mc::shared_ptr<smc_test_service>                              m_test_service;
    static std::unordered_map<std::string, std::shared_ptr<device_driver_t>> m_devices;
    static std::unordered_map<std::string, std::shared_ptr<device_driver_t>> m_i2c_devices;
    static root_object_ptr                                                   m_root_object;
    static void*                                                             m_driver_handle;
    static void*                                                             m_i2c_driver_handle;
};

mc::shared_ptr<smc_test_service> SmcAbiTest::m_test_service;
std::unordered_map<std::string, std::shared_ptr<device_driver_t>> SmcAbiTest::m_devices;
std::unordered_map<std::string, std::shared_ptr<device_driver_t>> SmcAbiTest::m_i2c_devices;
root_object_ptr                                                   SmcAbiTest::m_root_object;
void*                                                             SmcAbiTest::m_driver_handle = nullptr;
void*                                                             SmcAbiTest::m_i2c_driver_handle = nullptr;

// ========================= 基本功能测试 =========================

TEST_F(SmcAbiTest, register_device_driver_success) {
    // 验证驱动注册成功
    EXPECT_FALSE(m_devices.empty());
    EXPECT_TRUE(m_devices.find("Smc") != m_devices.end());

    auto smc_driver = m_devices["Smc"];
    EXPECT_NE(smc_driver, nullptr);
    EXPECT_STREQ(smc_driver->device_name, "Smc");
}

TEST_F(SmcAbiTest, init_smc_success) {
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x60, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建SMC内部对象
    std::string      smc_object_name = "test_smc_obj";
    mc::mutable_dict csr_object = create_smc_csr_object(0x60, 1, 1, 100, 100, 2, 1, 1, 3, 3);
    csr_object["object_name"]   = smc_object_name;
    auto smc_internal =
        dev::device_manager::get_instance().create_chip(smc_object_name, "Smc", csr_object);
    ASSERT_TRUE(smc_internal != nullptr);

    auto device_driver = m_devices["Smc"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(&m_test_service, smc_object_name.c_str());
    ASSERT_TRUE(device != nullptr);
    auto smc_obj = static_cast<dev::smc_object*>(device);

    auto i2c_driver = create_bus_driver("I2c");
    ASSERT_TRUE(i2c_driver != nullptr);

    // 连接I2C总线与驱动
    auto i2c_device = i2c_driver->ctor(&m_test_service, i2c_object_name.c_str());
    ASSERT_TRUE(i2c_device != nullptr);
    auto i2c_obj = static_cast<dev::I2c_object*>(i2c_device);

    auto bus_connector  = create_test_connector(1, 1, 1);
    auto chip_connector = create_test_connector(1, 1, 1);

    // 初始化I2C总线
    status_t ret = i2c_driver->init(i2c_device, &i2c_csr, &bus_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 初始化SMC芯片
    ret = device_driver->init(device, &csr_object, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 设置父对象
    i2c_obj->set_parent(m_root_object.get());
    smc_obj->set_parent(i2c_obj);

    // 注册对象到服务
    m_test_service->register_object(smc_obj);
    m_test_service->register_object(i2c_obj);

    // 设置连接关系
    smc_internal->set_left_bus(i2c_internal);
    smc_internal->set_host_bus(i2c_internal);

    // 验证初始化成功
    EXPECT_TRUE(smc_obj->m_interface_chip.m_chip != nullptr);

    device_driver->start(device);
    EXPECT_NO_THROW(device_driver->dump(device));
    device_driver->stop(device);
}

TEST_F(SmcAbiTest, init_smc_null_params) {
    auto smc_driver = m_devices["Smc"];

    // 测试空参数
    status_t ret = smc_driver->init(nullptr, nullptr, nullptr);
    EXPECT_EQ(ret, STATUS_ERROR);
}

TEST_F(SmcAbiTest, init_smc_null_device) {
    auto smc_driver = m_devices["Smc"];
    auto connector = create_test_connector();
    auto csr = create_smc_csr_object(0x20, 1, 1, 1000, 1000, 1, 0, 0, 3, 3);

    // 测试空设备句柄
    status_t ret = smc_driver->init(nullptr, &csr, &connector);
    EXPECT_EQ(ret, STATUS_ERROR);
}

TEST_F(SmcAbiTest, block_read_write) {
    // BlockWrite/BlockRead测试
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c_bit";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x60, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建SMC内部对象
    std::string      smc_object_name = "test_smc_bit_obj";
    mc::mutable_dict csr_object = create_smc_csr_object(0x60, 1, 1, 100, 100, 2, 1, 1, 3, 3);
    csr_object["object_name"]   = smc_object_name;
    auto smc_internal =
        dev::device_manager::get_instance().create_chip(smc_object_name, "Smc", csr_object);
    ASSERT_TRUE(smc_internal != nullptr);

    auto device_driver = m_devices["Smc"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(&m_test_service, smc_object_name.c_str());
    ASSERT_TRUE(device != nullptr);
    auto smc_obj = static_cast<dev::smc_object*>(device);

    auto i2c_driver = create_bus_driver("I2c");
    ASSERT_TRUE(i2c_driver != nullptr);
    auto i2c_device = i2c_driver->ctor(&m_test_service, i2c_object_name.c_str());
    ASSERT_TRUE(i2c_device != nullptr);
    auto i2c_obj = static_cast<dev::I2c_object*>(i2c_device);

    auto bus_connector  = create_test_connector(1, 1, 1);
    auto chip_connector = create_test_connector(1, 1, 1);

    // 初始化I2C总线
    status_t ret = i2c_driver->init(i2c_device, &i2c_csr, &bus_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 初始化SMC芯片
    ret = device_driver->init(device, &csr_object, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 设置父对象
    i2c_obj->set_parent(m_root_object.get());
    smc_obj->set_parent(i2c_obj);

    // 注册对象到服务
    m_test_service->register_object(i2c_obj);
    m_test_service->register_object(smc_obj);

    // 设置连接关系
    smc_internal->set_left_bus(i2c_internal);
    smc_internal->set_host_bus(i2c_internal);

    // 验证初始化成功
    EXPECT_TRUE(smc_obj->m_interface_chip.m_chip != nullptr);

    // 测试BlockWrite/BlockRead操作
    // 测试BlockWrite写入

    std::vector<uint8_t> write_data1 = {0x09, 0x00, 0x00, 0x33, 0x00, 0x33, 0x33, 0x33, 0x33, 0x33, 0xbf};
    // 读取数据, 通过I2C预写入数据, 然后通过SMC读取数据
    ACCESS_DATA_S write_data_req = {
        .addr_width = 1,
        .offset_width = 1,
        .mask = 0x00,
        .addr = 0x60,
        .offset = 0x21,
        .length = 0x0B,
        .in_buffer = write_data1,
        .out_buffer = {},
        .read_time_out = 100,
        .write_time_out = 100,
        .optype = 0,
    };
    uint32_t ret_code = i2c_internal->write(write_data_req);
    EXPECT_EQ(ret_code, 0);

    std::vector<uint8_t> expected_data = {0x00, 0x33, 0x00, 0x33, 0x33, 0x33, 0x33, 0x33};
    std::vector<uint8_t> read_data = smc_obj->m_interface_chip.BlockIORead(0x18000400, 0x09);
    EXPECT_EQ(read_data.size(), 0x08);

    for (int i = 0; i < read_data.size(); i++) {
        EXPECT_EQ(read_data[i], expected_data[i]);
    }

    // 测试SMC_WRITE_OPCODE
    EXPECT_NO_THROW(smc_obj->m_interface_chip.BlockIOWrite(0x18000400, {}));

    // 通过i2c bus读取数据, 验证SMC_WRITE_OPCODE
    ACCESS_DATA_S read_data_req_no_data = {
        .addr_width = 1,
        .offset_width = 1,
        .mask = 0x00,
        .addr = 0x60,
        .offset = 0x20,
        .length = 0x06,
        .in_buffer = {},
        .out_buffer = {},
        .read_time_out = 100,
        .write_time_out = 100,
        .optype = 0,
    };
    ret_code = i2c_internal->read(read_data_req_no_data);
    EXPECT_EQ(ret_code, 0);

    std::vector<uint8_t> expected_data_write = {0x04, 0x18, 0x00, 0x04, 0x00, 0xd3};
    EXPECT_EQ(read_data_req_no_data.out_buffer.size(), expected_data_write.size());
    for (int i = 0; i < read_data_req_no_data.out_buffer.size(); i++) {
        EXPECT_EQ(read_data_req_no_data.out_buffer[i], expected_data_write[i]);
    }

    // SMC_WRITE_OPCODE_WITH_DATA
    EXPECT_NO_THROW(smc_obj->m_interface_chip.BlockIOWrite(0x18000400, {0x01}));

    // 通过i2c bus读取数据, 验证SMC_WRITE_OPCODE_WITH_DATA
    ACCESS_DATA_S read_data_req_with_data = {
        .addr_width = 1,
        .offset_width = 1,
        .mask = 0x00,
        .addr = 0x60,
        .offset = 0x22,
        .length = 0x07,
        .in_buffer = {},
        .out_buffer = {},
        .read_time_out = 100,
        .write_time_out = 100,
        .optype = 0,
    };
    ret_code = i2c_internal->read(read_data_req_with_data);
    EXPECT_EQ(ret_code, 0);

    std::vector<uint8_t> expected_data_write_with_data = {0x05, 0x18, 0x00, 0x04, 0x00, 0x01, 0xA0};
    EXPECT_EQ(read_data_req_with_data.out_buffer.size(), expected_data_write_with_data.size());
    for (int i = 0; i < read_data_req_with_data.out_buffer.size(); i++) {
        EXPECT_EQ(read_data_req_with_data.out_buffer[i], expected_data_write_with_data[i]);
    }
}

TEST_F(SmcAbiTest, smc_forward) {
    // 先创建前级i2c内部对象
    std::string      i2c_a_object_name = "test_i2c_a";
    mc::mutable_dict i2c_a_csr         = create_bus_csr_object(0, 3400, 0, 0x60, false);
    i2c_a_csr["object_name"]           = i2c_a_object_name;
    auto i2c_a_internal =
        dev::device_manager::get_instance().create_bus(i2c_a_object_name, "I2c", i2c_a_csr);
    ASSERT_TRUE(i2c_a_internal != nullptr);

    // 创建两个SMC内部对象
    // 创建60地址上的SMC CHIP对象
    std::string      smc_a_object_name = "test_smc_a_obj";
    mc::mutable_dict csr_a = create_smc_csr_object(0x60, 1, 1, 100, 100, 2, 1, 1, 3, 3);
    csr_a["object_name"]   = smc_a_object_name;
    auto smc_a_internal =
        dev::device_manager::get_instance().create_chip(smc_a_object_name, "Smc", csr_a);
    ASSERT_TRUE(smc_a_internal != nullptr);

    // 创建80地址上的SMC CHIP对象
    std::string      smc_b_object_name = "test_smc_b_obj";
    mc::mutable_dict csr_b = create_smc_csr_object(0x80, 1, 1, 100, 100, 2, 1, 1, 3, 3);
    csr_b["object_name"]   = smc_b_object_name;
    auto smc_b_internal =
        dev::device_manager::get_instance().create_chip(smc_b_object_name, "Smc", csr_b);
    ASSERT_TRUE(smc_b_internal != nullptr);

    auto smc_driver = m_devices["Smc"];
    ASSERT_TRUE(smc_driver != nullptr);

    // 创建两个SMC资源树对象
    auto smc_a_device = smc_driver->ctor(&m_test_service, smc_a_object_name.c_str());
    auto smc_b_device = smc_driver->ctor(&m_test_service, smc_b_object_name.c_str());
    ASSERT_TRUE(smc_a_device != nullptr);
    ASSERT_TRUE(smc_b_device != nullptr);
    auto smc_a_obj = static_cast<dev::smc_object*>(smc_a_device);
    auto smc_b_obj = static_cast<dev::smc_object*>(smc_b_device);

    auto i2c_driver = create_bus_driver("I2c");
    ASSERT_TRUE(i2c_driver != nullptr);

    // 创建I2C和I2C MUX资源树对象
    auto i2c_a_device = i2c_driver->ctor(&m_test_service, i2c_a_object_name.c_str());
    ASSERT_TRUE(i2c_a_device != nullptr);
    auto i2c_a_obj = static_cast<dev::I2c_object*>(i2c_a_device);

    auto bus_connector  = create_test_connector(1, 1, 1);
    auto chip_connector = create_test_connector(1, 1, 1);

    // 初始化I2C总线和I2C MUX
    status_t ret = i2c_driver->init(i2c_a_device, &i2c_a_csr, &bus_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 初始化SMC对象
    ret = smc_driver->init(smc_a_device, &csr_a, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);
    ret = smc_driver->init(smc_b_device, &csr_b, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 设置父对象
    i2c_a_obj->set_parent(m_root_object.get());
    smc_a_obj->set_parent(i2c_a_obj);
    smc_b_obj->set_parent(smc_a_obj);

    // 注册对象到服务
    m_test_service->register_object(smc_a_obj);
    m_test_service->register_object(smc_b_obj);
    m_test_service->register_object(i2c_a_obj);

    // 设置连接关系 i2c_a_internal -> smc_a_internal -> smc_b_internal
    smc_a_internal->set_left_bus(i2c_a_internal);
    smc_a_internal->set_host_bus(i2c_a_internal);

    smc_b_internal->set_left_bus(i2c_a_internal);
    smc_b_internal->set_host_bus(i2c_a_internal);
    smc_b_internal->set_left_chip(smc_a_internal);

    EXPECT_TRUE(smc_a_obj->m_interface_chip.m_chip != nullptr);
    EXPECT_TRUE(smc_b_obj->m_interface_chip.m_chip != nullptr);

    // 测试底层SMC执行SMC_WRITE_OPCODE
    // 执行的i2c 命令应当是: 60 30 0b 80 06 04 00 20 04 18 00 04 00 bd 1d
    //                     bus op data
    EXPECT_NO_THROW(smc_b_obj->m_interface_chip.BlockIOWrite(0x18000400, {}));

    std::vector<uint8_t> expected_data_write =
        {0x0b, 0x80, 0x06, 0x04, 0x00, 0x20, 0x04, 0x18, 0x00, 0x04, 0x00, 0xbd, 0x1d};
    // 通过i2c bus读取实际数据, 验证SMC_WRITE_OPCODE_FORWARD
    ACCESS_DATA_S read_data_req_no_data = {
        .addr_width = 1,
        .offset_width = 1,
        .mask = 0x00,
        .addr = 0x60,
        .offset = 0x30,
        .length = static_cast<uint32_t>(expected_data_write.size()),
        .in_buffer = {},
        .out_buffer = {},
        .read_time_out = 100,
        .write_time_out = 100,
        .optype = 0,
    };
    uint32_t ret_code = i2c_a_internal->read(read_data_req_no_data);
    EXPECT_EQ(ret_code, 0);

    EXPECT_EQ(read_data_req_no_data.out_buffer.size(), expected_data_write.size());
    for (int i = 0; i < read_data_req_no_data.out_buffer.size(); i++) {
        EXPECT_EQ(read_data_req_no_data.out_buffer[i], expected_data_write[i]);
    }

    // 测试底层SMC执行SMC_WRITE_OPCODE_WITH_DATA
    EXPECT_NO_THROW(smc_b_obj->m_interface_chip.BlockIOWrite(0x18000400, {0x01}));
    // 执行的i2c 命令应当是: 60 30 0c 80 07 04 00 22 05 18 00 04 00 01 ad a9
    //                     bus op data
    std::vector<uint8_t> expected_data_write_with_data =
        {0x0c, 0x80, 0x07, 0x04, 0x00, 0x22, 0x05, 0x18, 0x00, 0x04, 0x00, 0x01, 0xad, 0xa9};
    // 通过i2c bus读取数据, 验证SMC_WRITE_OPCODE_FORWARD
    ACCESS_DATA_S read_data_req_with_data = {
        .addr_width = 1,
        .offset_width = 1,
        .mask = 0x00,
        .addr = 0x60,
        .offset = 0x30,
        .length = static_cast<uint32_t>(expected_data_write_with_data.size()),
        .in_buffer = {},
        .out_buffer = {},
        .read_time_out = 100,
        .write_time_out = 100,
        .optype = 0,
    };
    ret_code = i2c_a_internal->read(read_data_req_with_data);
    EXPECT_EQ(ret_code, 0);
    EXPECT_EQ(read_data_req_with_data.out_buffer.size(), expected_data_write_with_data.size());
    for (int i = 0; i < read_data_req_with_data.out_buffer.size(); i++) {
        EXPECT_EQ(read_data_req_with_data.out_buffer[i], expected_data_write_with_data[i]);
    }
}


TEST_F(SmcAbiTest, bit_read_write) {
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c_bit_a";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x60, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建SMC内部对象
    std::string      smc_object_name = "test_smc_bit_obj_a";
    mc::mutable_dict csr_object = create_smc_csr_object(0x60, 1, 1, 100, 100, 2, 1, 1, 3, 3);
    csr_object["object_name"]   = smc_object_name;
    auto smc_internal =
        dev::device_manager::get_instance().create_chip(smc_object_name, "Smc", csr_object);
    ASSERT_TRUE(smc_internal != nullptr);

    auto device_driver = m_devices["Smc"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(&m_test_service, smc_object_name.c_str());
    ASSERT_TRUE(device != nullptr);
    auto smc_obj = static_cast<dev::smc_object*>(device);

    auto i2c_driver = create_bus_driver("I2c");
    ASSERT_TRUE(i2c_driver != nullptr);
    auto i2c_device = i2c_driver->ctor(&m_test_service, i2c_object_name.c_str());
    ASSERT_TRUE(i2c_device != nullptr);
    auto i2c_obj = static_cast<dev::I2c_object*>(i2c_device);

    auto bus_connector  = create_test_connector(1, 1, 1);
    auto chip_connector = create_test_connector(1, 1, 1);

    // 初始化I2C总线
    status_t ret = i2c_driver->init(i2c_device, &i2c_csr, &bus_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 初始化SMC芯片
    ret = device_driver->init(device, &csr_object, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 设置父对象
    i2c_obj->set_parent(m_root_object.get());
    smc_obj->set_parent(i2c_obj);

    // 注册对象到服务
    m_test_service->register_object(i2c_obj);
    m_test_service->register_object(smc_obj);

    // 设置连接关系
    smc_internal->set_left_bus(i2c_internal);
    smc_internal->set_host_bus(i2c_internal);

    // 验证初始化成功
    EXPECT_TRUE(smc_obj->m_interface_chip.m_chip != nullptr);

    // 测试位读写操作
    // 测试位写入
    std::vector<uint8_t> write_data = {0xAA};
    smc_obj->m_interface_chip.BitIOWrite(0, 1, 0x0F, write_data);

    // 测试uint8_t读取
    std::vector<uint8_t> read_data = smc_obj->m_interface_chip.BitIORead(0, 1, 0xFFF);
    std::cout << "read_data: " << read_data.size() << std::endl;
    EXPECT_FALSE(read_data.empty());

    // 测试uint16_t写入
    std::vector<uint8_t> write_data2 = {0xBB, 0xAA};
    smc_obj->m_interface_chip.BitIOWrite(0, 2, 0xFFFF, write_data2);

    // 测试uint16_t读取
    std::vector<uint8_t> read_data2 = smc_obj->m_interface_chip.BitIORead(0, 2, 0xFFFF);
    std::cout << "read_data2: " << read_data2.size() << std::endl;
    EXPECT_FALSE(read_data2.empty());

    // 测试uint32_t写入
    std::vector<uint8_t> write_data3 = {0xDD, 0xCC, 0xBB, 0xAA};
    smc_obj->m_interface_chip.BitIOWrite(0, 4, 0xFFFFFFFF, write_data3);

    // 测试uint32_t读取
    std::vector<uint8_t> read_data3 = smc_obj->m_interface_chip.BitIORead(0, 4, 0xFFFFFFFF);
    std::cout << "read_data3: " << read_data3.size() << std::endl;
    EXPECT_FALSE(read_data3.empty());

    // 测试读取长度超过32位的数据, 应当返回空
    EXPECT_THROW(smc_obj->m_interface_chip.BitIORead(0, 9, 0x00), std::exception);

    // 测试读取长度为0的数据, 应当返回空
    EXPECT_NO_THROW(smc_obj->m_interface_chip.BitIORead(0, 0, 0x00));
}

TEST_F(SmcAbiTest, dt_dump) {
    // 先创建前级i2c内部对象
    std::string      i2c_object_name = "test_i2c_dump";
    mc::mutable_dict i2c_csr         = create_bus_csr_object(0, 3400, 0, 0x60, false);
    i2c_csr["object_name"]           = i2c_object_name;
    auto i2c_internal =
        dev::device_manager::get_instance().create_bus(i2c_object_name, "I2c", i2c_csr);
    ASSERT_TRUE(i2c_internal != nullptr);

    // 创建SMC内部对象
    std::string      smc_object_name = "test_smc_dump";
    mc::mutable_dict csr_object = create_smc_csr_object(0x60, 1, 1, 100, 100, 2, 1, 1, 3, 3);
    csr_object["object_name"]   = smc_object_name;
    auto smc_internal =
        dev::device_manager::get_instance().create_chip(smc_object_name, "Smc", csr_object);
    ASSERT_TRUE(smc_internal != nullptr);

    auto device_driver = m_devices["Smc"];
    ASSERT_TRUE(device_driver != nullptr);
    auto device = device_driver->ctor(&m_test_service, smc_object_name.c_str());
    ASSERT_TRUE(device != nullptr);
    auto smc_obj = static_cast<dev::smc_object*>(device);

    auto i2c_driver = create_bus_driver("I2c");
    ASSERT_TRUE(i2c_driver != nullptr);
    auto i2c_device = i2c_driver->ctor(&m_test_service, i2c_object_name.c_str());
    ASSERT_TRUE(i2c_device != nullptr);
    auto i2c_obj = static_cast<dev::I2c_object*>(i2c_device);

    auto bus_connector  = create_test_connector(1, 1, 1);
    auto chip_connector = create_test_connector(1, 1, 1);

    // 初始化I2C总线
    status_t ret = i2c_driver->init(i2c_device, &i2c_csr, &bus_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 初始化SMC芯片
    ret = device_driver->init(device, &csr_object, &chip_connector);
    ASSERT_EQ(ret, STATUS_OK);

    // 设置父对象
    i2c_obj->set_parent(m_root_object.get());
    smc_obj->set_parent(i2c_obj);

    // 注册对象到服务
    m_test_service->register_object(i2c_obj);
    m_test_service->register_object(smc_obj);

    // 设置连接关系
    smc_internal->set_left_bus(i2c_internal);
    smc_internal->set_host_bus(i2c_internal);

    // 验证初始化成功
    EXPECT_TRUE(smc_obj->m_interface_chip.m_chip != nullptr);
    const char* dump_result = device_driver->dump(device);
    EXPECT_NE(dump_result, nullptr);

    std::string dump_str = dump_result ? dump_result : "";
    EXPECT_FALSE(dump_str.empty());
}

} // namespace smc_test
} // namespace chip
} // namespace drivers 